
import React, {useEffect, useRef, useState} from 'react';
import ProTable, {ActionType, TableDropdown} from "@ant-design/pro-table";
import {PageContainer} from "@ant-design/pro-layout";
import {PlusOutlined } from '@ant-design/icons';
import Button from 'antd/lib/button';
import {Form, Image, message, Switch, TreeSelect} from 'antd';
import {getGoodsLists, getGoodsMenu, setGoodsPutAway} from "@/services/ant-design-pro/goods";
import {history} from "@@/core/history";
import ProForm, { ProFormSelect, ProFormText } from '@ant-design/pro-form';
import ProCard from '@ant-design/pro-card';

const GoodsLists2 = () => {

  const actionRef = useRef<ActionType>();
  const [search, setSearch] = useState({status: 1, include: 'productattrvalue,user'})
  const [formSearch, setFromSearch] = useState({})
  const [tableMenu,setTableMenu] = useState([])
  useEffect(()=>{
    // getGoodsMenu().then(res => {
    //   console.log(res)
    // })
    let res = [{
      "status": 1,
      "name": "出售中的商品",
      "count": 30
    }, {
      "status": 0,
      "name": "仓库中的商品",
      "count": 25
    }, {
      "stock": 0,
      "name": "已经售馨商品",
      "count": 1
    }, {
      "stock": "(lt)100",
      "name": "警戒库存商品",
      "count": 1
    }, {
      "serch": {deleted:'delete'},
      "name": "回收站的商品",
      "count": 0
    }];

    res = res.map((item,index) =>{
      item.key = index
      item.tab = item.name+'（'+item.count+')'
      return item
    })
    setTableMenu(res)
  },[])

  const treeData = [
    {
      title: 'Node1',
      value: '0-0',
      children: [
        {
          title: 'Child Node1',
          value: '0-0-1',
        },
        {
          title: 'Child Node2',
          value: '0-0-2',
        },
      ],
    },
    {
      title: 'Node2',
      value: '0-1',
    },
  ];



  const columns = [
    {
      title: '商品ID',
      dataIndex: 'id',
      search: false,
      align: 'center',
      width: 100,
      render: (text,record,index)=>{
        return (
          <div>
            {record.id}
          </div>
        )
      }
    },
    {
      title: '商品图',
      dataIndex: 'image',
      search: false,
      align: 'center',
      render: (_, record) => {
        return (
          <Image
            width={50}
            src={record.image}
          />
        );
      }
    },
    {
      title: '商品名称',
      dataIndex: 'product_name',
      search: false,
      align: 'center',
      width: 200,
    },
    {
      title: '商品售价',
      dataIndex: 'productattrvalue["ot_price"]',
      search: false,
      align: 'center',
      width: 100,
      render: (_, record) =>{

        return <span>{record?.productattrvalue?.ot_price ?? '未定义' }</span>
      }
    },
    {
      title: '库存',
      dataIndex: 'stock',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      search: false,
      align: 'center',
      width: 100,
    },
    {
      title: '商品分类',
      dataIndex: 'category_id',
      hideInTable: true,
      search: true,
      width: 100,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <TreeSelect
              style={{width: '100%'}}
              treeData={treeData}
              dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
              placeholder="Please select"
              treeDefaultExpandAll
              {...fieldProps}
            />
          );
        }
        return defaultRender(_);
      }

    },
    {
      title: '商品搜索',
      dataIndex: 'search',
      search: true,
      hideInTable: true,
      renderFormItem: (_, {defaultRender}) => {
        return defaultRender(_);
      },
    },
    {
      title: '销量',
      dataIndex: 'sales',
      align: 'center',
      search: false,
      width: 100,
      sorter: (a, b) => a.containers - b.containers,
    },
    {
      title: '状态',
      dataIndex: 'status',
      filters: true,
      onFilter: true,
      search: false,
      align: 'center',
      valueType: 'select',
      width: 100,
      render: (_, record) =>
        <Switch
          checkedChildren="上架"
          unCheckedChildren="下架"
          defaultChecked={record.status}
          onChange={async (state) => {
            console.log(state);
            setGoodsPutAway({
              ids: record.id,
              status: state ? 1 : 0,
            }).then(() => {
              message.success('操作成功！')
              actionRef.current.reload();
            })
          }
          }
        />
    },

    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => history.push('/manageGoods/editGoods/3433')}
        >
          编辑
        </a>,
        <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
          查看
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={() => action?.reload()}
          menus={[
            {key: 'copy', name: '复制'},
            {key: 'delete', name: '删除'},
          ]}
        />,
      ],
    },
  ];



  // @ts-ignore
  return (
    <PageContainer
      header={{
        title: '商品列表',
        breadcrumb: {},
      }}
      tabList={tableMenu}
      onTabChange={(key) => {
        let item =  tableMenu[key]
        setSearch({
          ...search, ...item.search})
        // switch (key) {
        //   case '1':
        //     setSearch({
        //       ...search, ...{
        //         status: 1
        //       }
        //     })
        //
        //     break;
        //   case '2':
        //     setSearch({
        //       ...search, ...{
        //         status: 0
        //       }
        //     })
        //     break;
        //   case '3':
        //     setSearch({
        //       ...search, ...{
        //         status: 3,
        //       }
        //     })
        //
        //
        //     break;
        //   case '4':
        //     setSearch({
        //       ...search, ...{
        //         status: 4
        //       }
        //     })
        //     break;
        //
        //   case '5':
        //     setSearch({
        //       ...search, ...{
        //         status: 5
        //       }
        //     })
        //     break;
        // }
        actionRef.current.reload();

      }}


    >
      <ProCard  bordered>
        <ProForm
          layout="inline"
          onFinish={values=>{
            setFromSearch(values)
            actionRef.current.reload();
          }}
        >
          <ProFormText name="title" label="名称" placeholder="请输入名称" />
        </ProForm>
      </ProCard>



      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => {
          return getGoodsLists({...params,...sort, ...filter,...search,...formSearch});
        }}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={false}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="高级表格"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary">
            新建
          </Button>
        ]}
      />
    </PageContainer>

  );
};

export default GoodsLists2;
